/**
 * 链动公排会员关系图
 * 用于显示会员树形结构关系图
 * 版本: 2.0
 * 更新时间: 2024-07-22
 */

// 全局变量
var memberChart = null;
var currentMemberData = null;

// 关闭弹窗
function closeself() {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

// 初始化图表
function initChart(chartData, options) {
    if (!chartData) {
        console.warn('图表数据为空');
        return;
    }

    var dom = document.getElementById("guanxitu");
    if (!dom) {
        console.error('未找到图表容器元素');
        return;
    }

    // 销毁已存在的图表实例
    if (memberChart) {
        memberChart.dispose();
    }

    memberChart = echarts.init(dom);
    currentMemberData = chartData;

    var defaultOptions = {
        backgroundColor: '#f8f9fa',
        tooltip: {
            trigger: 'item',
            triggerOn: 'mousemove',
            backgroundColor: 'rgba(0,0,0,0.85)',
            borderColor: '#667eea',
            borderWidth: 2,
            borderRadius: 8,
            textStyle: {
                color: '#fff',
                fontSize: 13,
                lineHeight: 20
            },
            padding: [12, 16],
            formatter: function(params) {
                var data = params.data;
                var html = '<div style="min-width: 200px;">';
                html += '<div style="font-weight: bold; font-size: 14px; margin-bottom: 8px; color: #667eea;">' + data.nickname + '</div>';
                html += '<div style="margin-bottom: 4px;">会员ID: <span style="color: #ffd93d;">' + data.member_id + '</span></div>';
                html += '<div style="margin-bottom: 4px;">推荐人ID: <span style="color: #6bcf7f;">' + data.pid + '</span></div>';
                if (data.up_pid && data.up_pid > 0) {
                    html += '<div style="margin-bottom: 4px;">公排上级ID: <span style="color: #ff6b6b;">' + data.up_pid + '</span></div>';
                }
                if (data.level) {
                    html += '<div style="margin-bottom: 4px;">层级: <span style="color: #4ecdc4;">' + data.level + '</span></div>';
                }
                if (data.position) {
                    html += '<div style="margin-bottom: 4px;">位置: <span style="color: #45b7d1;">' + data.position + '</span></div>';
                }
                if (data.children && data.children.length > 0) {
                    html += '<div style="margin-top: 8px; padding-top: 8px; border-top: 1px solid #555;">下级成员: <span style="color: #ffd93d;">' + data.children.length + '</span> 人</div>';
                }
                html += '<div style="margin-top: 8px; font-size: 12px; color: #aaa;">点击查看详细关系图</div>';
                html += '</div>';
                return html;
            }
        },
        series: [{
            type: 'tree',
            data: [chartData],
            left: '5%',
            right: '5%',
            top: '10%',
            bottom: '10%',
            symbol: function(value, params) {
                if (params.data.headimg && params.data.headimg !== '/static/img/touxiang.png') {
                    return 'image://' + params.data.headimg;
                } else {
                    return 'circle';
                }
            },
            symbolSize: function(value, params) {
                // 根据层级调整节点大小
                var level = params.data.level || 1;
                return Math.max(40, 60 - level * 3);
            },
            orient: 'vertical',
            expandAndCollapse: true,
            roam: true,
            initialTreeDepth: -1,
            itemStyle: {
                borderColor: function(params) {
                    // 根据不同条件设置不同颜色
                    if (params.data.is_fu) {
                        return '#ff6b6b'; // 财富点位用红色
                    } else if (params.data.level === 1) {
                        return '#667eea'; // 根节点用蓝色
                    } else {
                        return '#6bcf7f'; // 普通节点用绿色
                    }
                },
                borderWidth: 3,
                shadowColor: 'rgba(0,0,0,0.3)',
                shadowBlur: 8,
                shadowOffsetY: 3
            },
            lineStyle: {
                color: '#667eea',
                width: 2,
                curveness: 0.3,
                shadowColor: 'rgba(102, 126, 234, 0.3)',
                shadowBlur: 5
            },
            label: {
                position: 'bottom',
                verticalAlign: 'top',
                align: 'middle',
                fontSize: 11,
                color: '#333',
                fontWeight: 'bold',
                offset: [0, 18],
                backgroundColor: 'rgba(255,255,255,0.95)',
                borderColor: function(params) {
                    if (params.data.is_fu) {
                        return '#ff6b6b';
                    } else if (params.data.level === 1) {
                        return '#667eea';
                    } else {
                        return '#6bcf7f';
                    }
                },
                borderWidth: 1,
                borderRadius: 6,
                padding: [6, 10],
                shadowColor: 'rgba(0,0,0,0.1)',
                shadowBlur: 3,
                formatter: function(params) {
                    var data = params.data;
                    var text = data.nickname + '\nID:' + data.member_id;
                    if (data.is_fu) {
                        text += '\n(财富点位)';
                    }
                    return text;
                }
            },
            leaves: {
                label: {
                    position: 'bottom',
                    verticalAlign: 'top',
                    align: 'middle',
                    offset: [0, 18]
                }
            },
            emphasis: {
                focus: 'descendant',
                itemStyle: {
                    borderColor: '#ff6b6b',
                    borderWidth: 4,
                    shadowBlur: 12
                },
                lineStyle: {
                    color: '#ff6b6b',
                    width: 3
                },
                label: {
                    fontSize: 12,
                    fontWeight: 'bold'
                }
            },
            animationDuration: 1200,
            animationDurationUpdate: 800,
            animationEasing: 'cubicOut'
        }]
    };

    // 合并用户自定义选项
    var finalOptions = Object.assign(defaultOptions, options || {});

    memberChart.setOption(finalOptions, true);

    // 添加点击事件
    memberChart.on('click', function(params) {
        if (params.data && params.data.member_id) {
            navigateToMember(params.data.member_id);
        }
    });

    // 添加双击事件（展开/收起节点）
    memberChart.on('dblclick', function(params) {
        if (params.data && params.data.children) {
            // 这里可以添加展开/收起逻辑
            console.log('双击节点:', params.data.nickname);
        }
    });

    // 窗口大小改变时重新渲染
    window.addEventListener('resize', function() {
        if (memberChart) {
            memberChart.resize();
        }
    });

    return memberChart;
}

// 导航到指定会员
function navigateToMember(memberId) {
    if (!memberId) {
        layer.msg('会员ID无效');
        return;
    }

    var params = {mid: memberId};
    var isOpen = getQueryVariable('isopen');
    if (isOpen == "1") {
        params.isopen = 1;
    }

    // 显示加载提示
    var loadingIndex = layer.load(2, {
        content: '正在加载关系图...',
        success: function() {
            setTimeout(function() {
                location.hash = ns.hash("lian://shop/member/charts", params);
            }, 300);
        }
    });
}

// 搜索会员
function searchMember() {
    var input = document.getElementById('member_id_input');
    if (!input) {
        layer.msg('搜索框不存在');
        return;
    }

    var mid = input.value.trim();

    if (!mid) {
        layer.msg('请输入会员ID');
        input.focus();
        return;
    }

    // 验证输入是否为数字
    if (!/^\d+$/.test(mid)) {
        layer.msg('会员ID必须为数字');
        input.focus();
        return;
    }

    navigateToMember(mid);
}

// 跳转到上级
function goToParent(pid) {
    if (!pid) {
        layer.msg('上级信息不存在');
        return;
    }

    navigateToMember(pid);
}

// 跳转到根节点
function goToRoot() {
    layer.confirm('确定要跳转到根节点吗？', {
        icon: 3,
        title: '提示'
    }, function(index) {
        navigateToMember(1); // 假设根节点ID为1
        layer.close(index);
    });
}

// 刷新图表
function refreshChart() {
    if (memberChart) {
        memberChart.clear();
        if (currentMemberData) {
            initChart(currentMemberData);
        }
    } else {
        location.reload();
    }
}

// 全屏显示图表
function toggleFullscreen() {
    var container = document.getElementById('guanxitu');
    if (!container) return;

    if (!document.fullscreenElement) {
        container.requestFullscreen().then(function() {
            if (memberChart) {
                setTimeout(function() {
                    memberChart.resize();
                }, 100);
            }
        });
    } else {
        document.exitFullscreen();
    }
}

// 导出图表为图片
function exportChart() {
    if (!memberChart) {
        layer.msg('图表未初始化');
        return;
    }

    var url = memberChart.getDataURL({
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#fff'
    });

    var link = document.createElement('a');
    link.download = '会员关系图_' + new Date().getTime() + '.png';
    link.href = url;
    link.click();
}

// 获取URL参数
function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return false;
}

// 初始化事件监听
function initEventListeners() {
    // 搜索框回车事件
    var searchInput = document.getElementById('member_id_input');
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchMember();
            }
        });

        // 输入框获得焦点时选中所有文本
        searchInput.addEventListener('focus', function() {
            this.select();
        });
    }

    // 全屏状态变化监听
    document.addEventListener('fullscreenchange', function() {
        if (memberChart) {
            setTimeout(function() {
                memberChart.resize();
            }, 100);
        }
    });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化事件监听
    initEventListeners();

    // 如果页面中有会员数据，则初始化图表
    if (typeof memberData !== 'undefined' && memberData) {
        initChart(memberData);
    }
});

// 页面卸载时清理资源
window.addEventListener('beforeunload', function() {
    if (memberChart) {
        memberChart.dispose();
        memberChart = null;
    }
});
